﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using JustinAngel.Neurons.Framework;
using JustinAngel.Neurons.Framework.Navigation;
using JustinAngel.UnitedNationsNews.Framework;
using JustinAngel.UnitedNationsNews.ItemViewMoels;
using Ninject;
using JustinAngel.Neurons.Framework.Helpers;

namespace JustinAngel.UnitedNationsNews.Pages.ArticleList
{
    public class ArticleListViewModel : VViewModelBase
    {
        private const string RssPipeBaseUrl =
            @"http://pipes.yahoo.com/pipes/pipe.run?_id=733f43356fbc9268c9d0865dcab2a4bb&_render=json&feedurl=http://www.un.org/apps/news/rss/rss_";
        private const string RssPipeEndUrl = ".asp";


        [Inject]
        public IDialogService DialogService { get; set; }

        [Inject]
        public IWebRequestMaker WebRequestMaker { get; set; }

        [Inject]
        public IRssItemsToViewModelsTransformer RssItemsToViewModelsTransformer { get; set; }

        public override void OnDataSet()
        {
            base.OnDataSet();
            IsLoading = (RealData.ArticleViewModels == null);

            if (RealData.ArticleViewModels == null)
            {
                WebRequestMaker.StartWithCredentialsAndTimeout(
                RssPipeBaseUrl + RealData.RssName + RssPipeEndUrl,
                TimeSpan.FromSeconds(30),
                OnRssFeedCompleted,
                OnRssFeedFailed
                );
            }
        }

        private void OnRssFeedCompleted(Stream obj)
        {
            var rssRootItem = Services.DataService.DeserializeStreamToBusinessObject(obj.ReadToEnd());
            var rootModel = RssItemsToViewModelsTransformer.Transform(rssRootItem);

            RealData.ArticleViewModels = rootModel.Articles;
            BeginInvokeOnUIThread(() =>
            {
                RaisePropertyChanged(() => ArticleViewModels);
                IsLoading = false;
            });
        }

        private void OnRssFeedFailed()
        {
            if (_wasNavigateFrom)
                return; 

            DialogService.ShowMessageBox("We couldn't get the list of articles for this category. Please try again later.", "We're sorry", MessageBoxButton.OK);
            BeginInvokeOnUIThread(() => MessengerInstance.Send(new NavigateBackMessage()));
        }

        public SectionViewModel RealData { get { return (SectionViewModel)this.Data; } }

        public string Title
        {
            get { return RealData.DisplayName; }
        }

        public List<ArticleItemViewModel> ArticleViewModels
        {
            get { return RealData.ArticleViewModels; }
        }

        private bool _isLoading;
        public bool IsLoading
        {
            get { return _isLoading; }
            set
            {
                _isLoading = value;
                RaisePropertyChangedAndUpdateVSM(() => IsLoading, value);
            }
        }

        private bool _wasNavigateFrom = false;
        public override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs navigationEventArgs)
        {
            _wasNavigateFrom = true; 
            base.OnNavigatedFrom(navigationEventArgs);
        }

        protected override Type AutomaticallyTombstoneAndRestoreViewModelType
        {
            get { return typeof(SectionViewModel); }
        }

        protected override bool IsAutomaticallyTombstoneAndRestoreViewModel
        {
            get { return true;  }
        }
    }
}
